package thread;

public class SyncDemo2 {
    public static void main(String[] args) {
        Shop shop2 = new Shop();
        Shop shop1 = new Shop();
        Thread t1 = new Thread("张三") {
            public void run() {
                shop1.buy();
            }
        };
        Thread t2 = new Thread("李四") {
            public void run() {
                shop2.buy();
            }
        };
        t1.start();
        t2.start();

    }
}

class Shop {
    public void buy() {
        try {
            Thread t = Thread.currentThread();
            System.out.println(t.getName() + " is buying");
            Thread.sleep(2000);
            /*
            同步监视对象通常使用：临界资源
            意思就是：多个线程抢谁就锁谁
             */
            synchronized (this) {//（）中还可以是字符串常量值
                System.out.println(t.getName() + " is trying");
                Thread.sleep(2000);

            }
            System.out.println(t.getName() + " leaving");
            Thread.yield();

        } catch (InterruptedException e) {

        }

    }
}